<?php


namespace app\api\controller;

use app\common\business\User as UserBis;
use app\common\lib\Time;

class User extends AuthBase
{
    /**
     * 用户基本信息（AuthBase登录判断就将ID及姓名存储起来了所以此处没必要传递用户ID）
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index(){
       $user = (new UserBis())->getNormalUserById($this->userId);
       $resultUser = [
           "id" => $this->userId,
           "username" => $user["username"],
           "sex" => $user["sex"]
       ];
        return show(config('status.success'), 'OK', $resultUser);
    }

    /**
     * 用户信息更新
     * @return \think\response\Json
     */
    public function update(){
        $username = input("param.username", "", "trim");
        $sex = input("param.sex", 0, "intval");
        $data = [
            'username' => $username,
            'sex' => $sex
        ];
        $validate = (new \app\api\validate\User())->scene('update_user');
        if(!$validate->check($data)){
            return show(config('status.error'), $validate->getError());
        }
        $userBisObj = new UserBis();
        $user = $userBisObj->update($this->userId, $data);
        if(!$user){
            return show(config('status.error'), "更新失败");
        }
        // 原则上用户名只能修改一次 用户名被修改Redis中Token对应的用户信息也要更新
        $userInfo = $userBisObj->getNormalUserById($this->userId);
        $redisData = [
            'id' => $userInfo['id'],
            'username' => $username,
        ];
        $res = cache(config("redis.token_pre").$this->accessToken, $redisData, Time::userLoginExpiresTime($userInfo['type']));
        if(!$res){
            return show(config('status.error'), "Redis中Token用户信息更新失败");
        }
        return show(config('status.success'),"更新成功");
    }
}